package logic

import (
	"context"
	"errors"
	"furni-manage/goods/goods"
	"furni-manage/goods/internal/svc"
	"furni-manage/model/mysql"
	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsAddLogic) GoodsAdd(in *goods.GoodsAddRequest) (*goods.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line

	var data1 mysql.Goods
	tx := mysql.DB.Begin()
	if err := data1.FindGoodsByname(mysql.DB, in.GoodsName); err == nil {
		tx.Rollback()
		return nil, errors.New("商品已经存在")
	}

	brand := mysql.Brand{
		Name: in.BrandName,
	}
	brand.FindBrandByName(mysql.DB, in.BrandName)

	class := mysql.Class{
		Name: in.ClassName,
	}
	class.FindClassByName(mysql.DB, in.ClassName)

	data := mysql.Goods{
		Name:    in.GoodsName,
		Price:   float64(in.Price),
		Num:     in.Num,
		Image:   in.Image,
		ClassId: int64(class.ID),
		BrandId: int64(brand.ID),
	}
	if err := data.GoodsAdd(mysql.DB); err != nil {
		tx.Rollback()
		return nil, err
	}
	tx.Commit()
	return &goods.GoodsAddResponse{
		GoodsId: int64(data.ID),
	}, nil
}
